﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using PccCommonForC;
using System.Xml;
using System.Text;
using System.IO;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Text.RegularExpressions;
using bs_ShowRoom;
using System.Configuration;
using System.Collections;
using System.Security.Cryptography;
using System.Net.Mail;

namespace ShowRoom.admin
{
    public partial class AddUser : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["user_id"] != "" && Request.QueryString["user_id"] != null)
                {
                    trPass.Visible = false;
                    trPassC.Visible = false;
                    txtEmail.Enabled = false;
                    txtuser.Enabled = false;
                }

                GetInUser();                
            }
        }
        #region "kiểm tra email hợp lệ"
        [Ajax.AjaxMethod()]
        public string CheckMail(string email)
        {
            string pattern = @"^[_a-zA-Z0-9][_.a-zA-Z0-9]*@[-.a-zA-Z0-9]+(\.[_.a-zA-Z0-9]+)*\.(com|edu|info|gov|int|mil|net|org|biz|name|museum|coop|aero|pro|tv|vn|[a-zA-Z]{2})$";
            Regex check = new Regex(pattern, RegexOptions.IgnorePatternWhitespace);
            bool valid = false;
            string kq = "";
            if (string.IsNullOrEmpty(email))
            {
                valid = false;
                kq = "0";
            }
            else
            {
                valid = check.IsMatch(email.ToLower());
            }
            if (valid == true)
            {
                kq = "1";
                bs_user myBs = new bs_user(ConfigurationManager.ConnectionStrings["ShowRoomConnectionString"].ToString());
                PccMsg myMsg = new PccMsg();
                myMsg.CreateFirstNode("user_name", "");
                myMsg.CreateFirstNode("email", email);
                myMsg.CreateFirstNode("Type", "1");
                string strXML = myMsg.GetXmlStr;
                string strReturn = myBs.DoReturnStr("TESTUSER_EMAIL", strXML, "");
                myMsg.LoadXml(strReturn);
                if (myMsg.Query("Err") == "N" || myMsg.Query("Err") == "F")
                {
                    kq = "1";
                }
                else
                {
                    kq = "2";
                }
            }
            else
                kq = "0";
            return kq;
        }
        #endregion

        #region "Kiểm tra user - email hợp lệ"
        [Ajax.AjaxMethod()]
        public string TestUser_Email(string user_email, string type)
        {
            string ok = "";
            bs_user myBs = new bs_user(ConfigurationManager.ConnectionStrings["ShowRoomConnectionString"].ToString());
            PccMsg myMsg = new PccMsg();
            myMsg.CreateFirstNode("user_name", user_email);
            myMsg.CreateFirstNode("name", user_email);
            myMsg.CreateFirstNode("Type", type);
            string strXML = myMsg.GetXmlStr;
            string strReturn = myBs.DoReturnStr("TESTUSER_EMAIL", strXML, "");
            myMsg.LoadXml(strReturn);

            if (myMsg.Query("Err") == "N" || myMsg.Query("Err") == "F")
            {
                ok = "1";
            }
            else
            {
                ok = "0";
            }
            return ok;
        }
        #endregion

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string email = CheckMail(txtEmail.Text.ToString().Trim());

            if (Request.QueryString["user_id"] == "" && Request.QueryString["user_id"] == null)
            {
                if (txtPass.Text == "" || txtPassC.Text == "")
                {
                    lblPassIn.Text = "nhập mật khẩu !";
                    // Response.Write("<script>alert('Email đả tồn tại')</script>");
                    return;
                }
                if (email == "2")
                {
                    lblEmailIn.Text = "email đả tồn tại !";
                    // Response.Write("<script>alert('Email đả tồn tại')</script>");
                    return;
                }
                string username = TestUser_Email(txtuser.Text.ToString().Trim(), "0");
                if (username == "0")
                {
                    lblUserIn.Text = "user đả tồn tại !";
                    //Response.Write("<script>alert('Tên đăng nhập đả tồn tại')</script>");
                    return;
                }
            }
            string user_id = "0";
            string birthday ="";
            string emailPass = "";
            string active=ddlActive.SelectedValue.Trim();
            string Type="0";
            if (Request.QueryString["user_id"] != "" && Request.QueryString["user_id"] != null)
            {
                Type = "4";
                user_id = Request.QueryString["user_id"].ToString().Trim();
            }

            string ok = SaveData(user_id,txtuser.Text.ToString().Trim(), txtPass.Text.ToString().Trim(), txtTen.Text.ToString().Trim(), txtsdt.Text.ToString().Trim(), txtEmail.Text.ToString().Trim(), ddlSex.SelectedValue.Trim(), "", txtDiaChi.Text.ToString().Trim(), birthday, "N", txtEmail.Text.ToString().Trim(), active, Type);
            if (ok == "F" || ok == "")
            {
                string Mes="";
                if(ok=="F")
                    Mes="Đăng ký thành công !";
                else
                    Mes="Cập nhật thành công !";
                string url = "user.aspx";
               // Response.Write("<script>alert('Quý khách đã đăng ký thành công tài khoản tại showroommypham.com !');window.location='login.aspx?&name=" + txtuser.Text.ToString().Trim() + "'</script>");
                ScriptFunction.ShowMsgTranOpennerUrl_ScriptManager(Mes, Page, url);
            }
            else
            {
                Response.Write("<script>alert('Đả có lỗi xãy ra trong quá trình đăng ký !')</script>");
                return;
            }
        }

        #region "Save Data"
        public string SaveData(string user_id,string user_name, string password, string name, string phone, string email, string sex, string introduction, string adress, string birthday, string activeEmail, string emailPass, string active, string Type)
        {
            bs_user myBs = new bs_user(ConfigurationManager.ConnectionStrings["ShowRoomConnectionString"].ToString());
            PccMsg myMsg = new PccMsg();
            myMsg.CreateFirstNode("user_id", user_id);
            myMsg.CreateFirstNode("name", name);
            myMsg.CreateFirstNode("username", user_name);
            myMsg.CreateFirstNode("password", password);
            myMsg.CreateFirstNode("ipassword", password);
            myMsg.CreateFirstNode("email", email);
            myMsg.CreateFirstNode("adress", adress);
            myMsg.CreateFirstNode("birthday", birthday);
            myMsg.CreateFirstNode("telephone", phone);
            myMsg.CreateFirstNode("sex", sex);
            myMsg.CreateFirstNode("company", "");
            myMsg.CreateFirstNode("point", "10");
            myMsg.CreateFirstNode("note", introduction);
            myMsg.CreateFirstNode("activeEmail", activeEmail);
            myMsg.CreateFirstNode("emailPass", EncryptMD5(emailPass));
            myMsg.CreateFirstNode("active", active);
            myMsg.CreateFirstNode("Type", Type);
            string strXML = myMsg.GetXmlStr;
            string strReturn = myBs.DoReturnStr("INSUPDUSER", strXML, "");
            myMsg.LoadXml(strReturn);


            return myMsg.Query("Err");
        }

        #endregion

        #region Ma Hoa Pass
        public static string EncryptMD5(string cleanString)
        {
            Byte[] clearBytes = null;
            clearBytes = new UnicodeEncoding().GetBytes(cleanString);
            Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
            string hashedText = BitConverter.ToString(hashedBytes);
            return hashedText;
        }
        #endregion

        #region "Thông tin user"
        private void GetInUser()
        {
            string user_id = "0";
            if (Request.QueryString["user_id"] != "" && Request.QueryString["user_id"] != null)
                user_id = Request.QueryString["user_id"].ToString().Trim();
            DataTable dt_ = GetInfouser(user_id, "1");
            if (dt_.Rows.Count > 0)
            {
                txtTen.Text = dt_.Rows[0]["name"].ToString().Trim();
                txtuser.Text = dt_.Rows[0]["username"].ToString().Trim();
                txtPass.Text = dt_.Rows[0]["password"].ToString().Trim();
                txtPassC.Text = dt_.Rows[0]["password"].ToString().Trim();
                txtEmail.Text = dt_.Rows[0]["email"].ToString().Trim();
                txtsdt.Text = dt_.Rows[0]["telephone"].ToString().Trim();
                txtDiaChi.Text = dt_.Rows[0]["adress"].ToString().Trim();
                ddlSex.SelectedValue= dt_.Rows[0]["sex"].ToString().Trim();
                ddlActive.SelectedValue = dt_.Rows[0]["active"].ToString().Trim();
            }
        }
        private DataTable GetInfouser(string user_id, string Type)
        {
            bs_menu mybs = new bs_menu(ConfigurationManager.ConnectionStrings["ShowRoomConnectionString"].ToString());
            PccMsg myMsg = new PccMsg();
            myMsg.CreateFirstNode("user_id", user_id);
            myMsg.CreateFirstNode("Type", Type);
            DataSet ds = mybs.DoReturnDataSet("GETPOWESUSER", myMsg.GetXmlStr, "");

            DataTable dt = new DataTable();
            if (ds.Tables.Count > 0)
                dt = ds.Tables[0];

            return dt;

        }
        #endregion

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Write("<script>window.close();</script>");
        }
    }
}